//
//  HMHomeTableViewController.swift
//  Weibo
//
//  Created by itteacher on 2017/7/22.
//  Copyright © 2017年 itteacher. All rights reserved.
//

import UIKit
import YYModel

class HMHomeTableViewController: HMVisitorTableViewController {

    //  数据源
//    lazy var statusList: [HMStatus] = [HMStatus]()
    
    //引用ViewModel
    fileprivate lazy var homeViewModel: HMHomeVewModel = HMHomeVewModel()
    //  MARK: --   懒加载控件(小菊花)
    fileprivate lazy var pullUpView: UIActivityIndicatorView = {
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        indicatorView.color = UIColor.red
        return indicatorView
    }()
    
    //下拉刷新控件
    fileprivate lazy var pullDownView: HMRefreshControl = {
        
        let refreshCtr = HMRefreshControl()
        //添加事件
        refreshCtr.addTarget(self, action: #selector(pullDownRefreshing), for: .valueChanged)
        return refreshCtr
    }()
    //tipLabel
    fileprivate lazy var tipLabel: UILabel = {
       let label = UILabel(fontSize: 12, textColor: UIColor.white)
        label.backgroundColor = UIColor.orange
        label.text = "没有加载到最新微博数据"
        label.textAlignment = .center
        //默认隐藏
        label.isHidden = true
        return label
    }()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLogin {
            //  没有登录修改访客视图信息
            visitorView?.updateVisitorInfo(message: nil, imageName: nil)
        } else {
            setupUI()
            //  登录
            loadData()
        }
    }
    
    private func setupUI() {
        
        if let nav  = self.navigationController {
                nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
                //nav.navigationBar.frame.maxY: 视图的最大y
                tipLabel.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY-35, width: nav.navigationBar.width, height: 35)
            }
            setupTableView()
        }

    
    //  设置tableView相关操作
    private func setupTableView() {
        //  注册cell
        tableView.register(HMHomeTableViewCell.self, forCellReuseIdentifier: HomeCellIdentifier)
        
        //设置cell高度,自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
         //  设置预估高度
        tableView.estimatedRowHeight = 200
        
        //去掉分割线
        tableView.separatorStyle = .none
        
        //  设置上拉加载视图
        tableView.tableFooterView = pullUpView
        
        //  设置系统下拉刷新方式2
        tableView.addSubview(pullDownView)
        
    }

    
    //  加载微博数据
    func loadData() {
        //   pullUpView.isAnimating : 如果执行风火轮动画，那么返回true，也就是上拉加载，否则不是上拉加载
        homeViewModel.loadData(isUp: pullUpView.isAnimating) { (isSuccess, message) in
            if self.pullUpView.isAnimating == false {
                //执行tip动画
                self.startTipAnimation(message: message)
            }
            //  结束刷新
            self.endRefreshing()
            if isSuccess {
                
                self.tableView.reloadData()
            }
            
        }
    }
        //MARK: -- 开启tip动画
        private func startTipAnimation(message: String) {
            
            //  如果控件显示表示正在执行动画，代码直接return
            if tipLabel.isHidden == false {
                return
            }
            
            //  执行动画显示
            tipLabel.isHidden = false
            //  设置消息内容
            tipLabel.text = message
            
            UIView.animate(withDuration: 1, animations: {self.tipLabel.transform = CGAffineTransform(translationX: 0, y: self.tipLabel.height)}) { (_) in
                UIView.animate(withDuration: 1, animations: {self.tipLabel.transform = CGAffineTransform.identity}, completion: { (_) in
                    //执行完动画隐藏
                    self.tipLabel.isHidden = true
                })
            }
        }
    
    @objc private func pullDownRefreshing() {
        
        loadData()
    }
    
    //  结束刷新
    private func endRefreshing() {
        //  停止风火轮
        pullUpView.stopAnimating()
        pullDownView.endRefreshing()
    }
}

extension HMHomeTableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: HomeCellIdentifier, for: indexPath) as! HMHomeTableViewCell
        //  获取模型
        let statusViewModel = homeViewModel.statusList[indexPath.row]
        cell.statusViewModel = statusViewModel
        return cell
    }
    
    //  将要显示的cell
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == homeViewModel.statusList.count - 1 && pullUpView.isAnimating == false {
            print("滚动到最后一个cell")
            //  开启风火轮
            pullUpView.startAnimating()
            //  微博数据
            loadData()
        }
    }
    
}

